<template>
    <BasicLayout>
        <template #wrapper>
            <el-card class="box-card">
                <template v-if="userId === -1">
                    <el-form
                        ref="queryForm"
                        :model="queryParams"
                        :inline="true"
                        label-width="70px"
                    >
                        <el-form-item label="店铺名称" prop="shopName">
                            <el-input
                                v-model="queryParams.shopName"
                                placeholder="请输入店铺名称"
                                clearable
                                size="small"
                                @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="订单时间" prop="recordAt">
                            <el-date-picker
                                v-model="queryParams.recordAt"
                                type="date"
                                placeholder="选择日期"
                                value-format="yyyy-MM-dd"
                            >
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="是否结算" prop="isPay">
                            <el-select
                                v-model="queryParams.isPay"
                                placeholder="是否结算"
                                clearable
                                size="small"
                            >
                                <el-option label="已结算" value="T" />
                                <el-option label="未结算" value="F" />
                            </el-select>
                        </el-form-item>

                        <el-form-item>
                            <el-button
                                type="primary"
                                icon="el-icon-search"
                                size="mini"
                                @click="handleQuery"
                                >搜索</el-button
                            >
                            <el-button
                                icon="el-icon-refresh"
                                size="mini"
                                @click="resetQuery"
                                >重置</el-button
                            >
                        </el-form-item>
                    </el-form>

                    <el-row :gutter="10" class="mb8">
                        <el-col :span="1.5">
                            <el-button
                                type="primary"
                                icon="el-icon-upload"
                                size="mini"
                                :disabled="!ids.length"
                                @click="batchSettlement"
                                v-permisaction="['platform:ordertoday:pay']"
                                >批量结算</el-button
                            >
                        </el-col>
                        <el-col :span="1.5">
                            <el-button
                                type="success"
                                icon="el-icon-scissors"
                                size="mini"
                                :disabled="!ids.length"
                                @click="batchRevoke"
                                v-permisaction="['platform:ordertoday:pay']"
                                >撤销结算</el-button
                            >
                        </el-col>
                    </el-row>

                    <el-row
                        class="card_wrap"
                        style="padding-bottom: 15px"
                        :gutter="5"
                    >
                        <el-col :span="3">
                            <el-card header="总单量">
                                <div>{{ summarizing.orderNum }}</div>
                            </el-card>
                        </el-col>
                        <el-col :span="3">
                            <el-card header="总返现">
                                <div>
                                    {{
                                        (summarizing.returnPrice || 0).toFixed(
                                            2
                                        )
                                    }}
                                </div>
                            </el-card>
                        </el-col>
                        <el-col :span="3">
                            <el-card header="实际总返现">
                                <div>
                                    {{
                                        (
                                            summarizing.realityReturnPrice || 0
                                        ).toFixed(2)
                                    }}
                                </div>
                            </el-card>
                        </el-col>
                        <el-col :span="3">
                            <el-card header="总佣金">
                                <div>
                                    {{
                                        (
                                            summarizing.totalBrokerage || 0
                                        ).toFixed(2)
                                    }}
                                </div>
                            </el-card>
                        </el-col>
                        <el-col :span="3">
                            <el-card header="总抠钱">
                                <div>
                                    {{
                                        (
                                            summarizing.totalDeductMoney || 0
                                        ).toFixed(2)
                                    }}
                                </div>
                            </el-card>
                        </el-col>
                        <el-col :span="3">
                            <el-card header="总利润">
                                <div>
                                    {{
                                        (summarizing.totalProfits || 0).toFixed(
                                            2
                                        )
                                    }}
                                </div>
                            </el-card>
                        </el-col>
                        <el-col :span="3">
                            <el-card header="商家数">
                                <div>{{ summarizing.shopNum }}</div>
                            </el-card>
                        </el-col>
                        <el-col :span="3">
                            <el-card header="代收款">
                                <div>
                                    {{
                                        (summarizing.totalShopPay || 0).toFixed(
                                            2
                                        )
                                    }}
                                </div>
                            </el-card>
                        </el-col>
                    </el-row>
                </template>
                <el-table
                    v-loading="loading"
                    :data="bworderList"
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column
                        type="selection"
                        width="55"
                        align="center"
                    />
                    <el-table-column
                        label="店铺名称"
                        align="center"
                        prop="shopName"
                        :show-overflow-tooltip="true"
                    />
                    <el-table-column
                        label="联系方式"
                        align="center"
                        prop="phone"
                        :show-overflow-tooltip="true"
                    />
                    <el-table-column
                        label="图片"
                        align="center"
                        prop="shopCover"
                        width="80"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <div>
                                <el-image
                                    style="width: 80px; height: 80px"
                                    :src="scope.row.shopCover"
                                />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="地址"
                        align="center"
                        width="200"
                        prop="shopAddress"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <span>{{
                                scope.row.shopAddress.replaceAll(" ", "")
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="订单数量"
                        align="center"
                        prop="orderNum"
                        :show-overflow-tooltip="true"
                    />
                    <el-table-column
                        label="活动总返现"
                        align="center"
                        prop="returnPrice"
                        width="110"
                        :show-overflow-tooltip="true"
                    />
                    <el-table-column
                        label="活动实际总返现"
                        align="center"
                        prop="returnPrice"
                        width="120"
                        :show-overflow-tooltip="true"
                    />
                    <el-table-column
                        label="总计佣金"
                        align="center"
                        prop="totalBrokerage"
                        :show-overflow-tooltip="true"
                    />
                    <el-table-column
                        label="总抠钱"
                        align="center"
                        prop="TotalDeductMoney"
                        :show-overflow-tooltip="true"
                    />
                    <el-table-column
                        label="汇总"
                        align="center"
                        prop="allPrice"
                        :show-overflow-tooltip="true"
                    />
                    <el-table-column
                        label="日期"
                        align="center"
                        prop="recordAt"
                        width="100"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <span>{{ scope.row.recordAt.split("T")[0] }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="结算状态"
                        align="center"
                        prop="isPay"
                        fixed="right"
                        class-name="small-padding fixed-width bgf8"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <el-tag
                                :type="
                                    scope.row.isPay === 'T'
                                        ? 'success'
                                        : 'danger'
                                "
                                >{{
                                    scope.row.isPay === "T"
                                        ? "已结算"
                                        : "未结算"
                                }}</el-tag
                            >
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        align="center"
                        fixed="right"
                        class-name="small-padding fixed-width bgf8"
                    >
                        <template slot-scope="scope">
                            <el-button
                                v-if="scope.row.isPay === 'F'"
                                size="mini"
                                type="text"
                                @click="settlement(scope.row)"
                                :loading="scope.row.loading"
                                v-permisaction="['platform:ordertoday:pay']"
                                >去结算</el-button
                            >
                            <el-button
                                v-else
                                size="mini"
                                type="text"
                                @click="cancelsettlement(scope.row)"
                                :loading="scope.row.loading"
                                v-permisaction="['platform:ordertoday:pay']"
                                >撤销结算</el-button
                            >
                            <el-button
                                size="mini"
                                type="text"
                                @click="exportFile(scope.row)"
                                v-permisaction="['platform:ordertoday:pay']"
                                >导出</el-button
                            >
                            <el-button
                                size="mini"
                                type="text"
                                @click="selPage(scope.row)"
                                v-permisaction="['platform:ordertoday:pay']"
                                >查看商家页</el-button
                            >
                            <el-button
                                size="mini"
                                type="text"
                                @click="copyPage(scope.row)"
                                v-permisaction="['platform:ordertoday:pay']"
                                >复制链接</el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>

                <pagination
                    v-show="total > 0"
                    :total="total"
                    :page.sync="queryParams.pageIndex"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"
                />
            </el-card>

            <textarea
                type="text"
                id="copy_input"
                style="
                    width: 10px;
                    height: 10px;
                    position: fixed;
                    left: -1000vw;
                    top: -1000vh;
                "
            />
        </template>
    </BasicLayout>
</template>

<script>
import {
    getShopDayOrder,
    payShopDayOrder,
    getSummarizing,
} from "@/api/bw/platform/shop/shop";
import {
    businessGetOrderInfo,
} from "@/api/bw/platform/order/order";

export default {
    name: "Config",
    props: {
        userId: {
            type: [Number, String],
            default: -1,
        },
        shopId: {
            type: [Number, String],
            default: -1,
        },
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            isEdit: false,
            isVerify: false,
            // 类型数据字典
            typeOptions: [],
            bworderList: [],
            orderStatusOptions: [],
            // 查询参数
            queryParams: {
                pageIndex: 1,
                pageSize: 10,
                shopName: "",
                recordAt: "",
                isPay: "",
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                // totalPrice: [{ required: true, message: '订单总金额不能为空', trigger: 'blur' }],
                returnPrice: [
                    {
                        required: true,
                        message: "返还金额不能为空",
                        trigger: "blur",
                    },
                ],
                orderStatus: [
                    {
                        required: true,
                        message: "订单状态不能为空",
                        trigger: "blur",
                    },
                ],
                // phone: [{ required: true, message: '手机号码不能为空', trigger: 'blur' }]
            },
            reasonList: [],
            summarizing: {},
            selection: [],
        };
    },
    computed: {
        srcList() {
            return (this.form.imageList || []).map((item) => {
                return item.imageUrl;
            });
        },
    },
    created() {
        this.getList();
        this.getDicts("order_status").then((response) => {
            this.orderStatusOptions = response.data;
        });
        getSummarizing().then((res) => {
            this.summarizing = res.data || {};
        });
    },
    methods: {
        exportFile(row) {
            this.$confirm(`确定要导出该数据?`, "提示", {
                type: "warning",
            })
                .then(() => {
                    window.open(
                        process.env.VUE_APP_BASE_API +
                            "/api/v1/bw/exportShopOrderCode/" +
                            row.shopId +
                            "/" +
                            row.recordAt.split("T")[0]
                    );
                })
                .catch(() => {});
        },
        selPage(row) {
            window.open(
                `https://laoskj.cn/h5/index.html#/pages/business-bill/business-bill?shopId=${
                    row.shopId
                }&recordAt=${row.recordAt.split("T")[0]}`
            );
        },
        copyPage(row) {
            let notify = this.$notify({
                title: "提示",
                message: "正在复制中，请稍后",
                duration: 0,
            });
            let recordAt = row.recordAt.split("T")[0];
            businessGetOrderInfo({
                shopId: row.shopId,
                recordAt
            })
                .then((res) => {
                    if (res.code === 200) {
                        res = res.data
                        let dom = document.querySelector("#copy_input");
                        dom.value = `好汇吃对账单
门店：${row.shopName}
日期： ${recordAt}
成单量： ${res.num}单 | 佣金：${(res.totalBrokerage || 0).toFixed(2)}元
总返现： ${(res.returnPrice || 0).toFixed(2)} | 总费用：${(
                            res.totalPrice || 0
                        ).toFixed(2)}元
----------------------------------
请点击下方链接查看明细
----------------------------------
https://laoskj.cn/h5/index.html#/pages/business-bill/business-bill?shopId=${
                            row.shopId
                        }&recordAt=${recordAt}
----------------------------------
老板，这是结算账单，麻烦今天核对结算一下哦，转群里就可以了，谢谢
祝您生意兴隆`;
                        dom.select();
                        document.execCommand("copy");
                        this.$message.success("已复制");
                    }
                    notify.close();
                })
                .catch(() => {
                    notify.close();
                });
        },
        batchSettlement() {
            this.$confirm(`确定给 ${this.ids.length}个店铺 结算?`, "提示", {
                type: "warning",
            })
                .then(() => {
                    let notify = this.$notify({
                        title: "提示",
                        message: "正在结算中，请勿重复点击",
                        duration: 0,
                    });
                    let data = [];
                    this.selection.forEach((item) => {
                        data.push({
                            recordAt: item.recordAt.split("T")[0],
                            shopId: item.shopId,
                        });
                    });
                    payShopDayOrder({
                        orderPay: data,
                        isPay: "T",
                    }).then((res) => {
                        notify.close();
                        if (res.code === 200) {
                            this.msgSuccess("结算成功");
                            this.getList();
                        } else {
                            this.msgError(res.msg);
                        }
                    });
                })
                .catch(() => {});
        },
        batchRevoke() {
            this.$confirm(`确定撤销 ${this.ids.length}个店铺 的结算?`, "提示", {
                type: "warning",
            })
                .then(() => {
                    let notify = this.$notify({
                        title: "提示",
                        message: "正在撤销结算中，请勿重复点击",
                        duration: 0,
                    });
                    let data = [];
                    this.selection.forEach((item) => {
                        data.push({
                            recordAt: item.recordAt.split("T")[0],
                            shopId: item.shopId,
                        });
                    });
                    payShopDayOrder({
                        orderPay: data,
                        isPay: "F",
                    }).then((res) => {
                        notify.close();
                        if (res.code === 200) {
                            this.msgSuccess("撤销结算成功");
                            this.getList();
                        } else {
                            this.msgError(res.msg);
                        }
                    });
                })
                .catch(() => {});
        },
        cancelsettlement(row) {
            this.$confirm(`确定要撤销结算?`, "提示", {
                type: "warning",
            })
                .then(() => {
                    row.loading = true;
                    payShopDayOrder({
                        orderPay: [
                            {
                                recordAt: row.recordAt.split("T")[0],
                                shopId: row.shopId,
                            },
                        ],
                        isPay: "F",
                    })
                        .then((res) => {
                            if (res.code === 200) {
                                this.msgSuccess("撤销成功");
                                this.getList();
                            } else {
                                this.msgError(res.msg);
                            }
                            row.loading = false;
                        })
                        .catch(() => {
                            row.loading = false;
                        });
                })
                .catch(() => {});
        },
        settlement(row) {
            this.$confirm(`确定要结算?`, "提示", {
                type: "warning",
            })
                .then(() => {
                    row.loading = true;
                    payShopDayOrder({
                        orderPay: [
                            {
                                recordAt: row.recordAt.split("T")[0],
                                shopId: row.shopId,
                            },
                        ],
                        isPay: "T",
                    })
                        .then((res) => {
                            if (res.code === 200) {
                                this.msgSuccess("结算成功");
                                this.getList();
                            } else {
                                this.msgError(res.msg);
                            }
                            row.loading = false;
                        })
                        .catch(() => {
                            row.loading = false;
                        });
                })
                .catch(() => {});
        },

        querySearch(queryString, cb) {
            cb(
                this.reasonList.filter(
                    (item) => item.reason.indexOf(queryString) !== -1
                )
            );
        },
        handleSelect() {},
        /** 查询参数列表 */
        getList() {
            this.loading = true;
            let data = this.addDateRange(this.queryParams, this.dateRange);
            if (this.userId !== -1) {
                data.userId = this.userId;
            }
            if (this.shopId !== -1) {
                data.shopId = this.shopId;
            }
            getShopDayOrder(data).then((response) => {
                this.bworderList = response.data.list.map((item) => {
                    item.loading = false;
                    return item;
                });
                this.total = response.data.count;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                orderId: undefined,
                shopId: undefined,
                userId: undefined,
                orderSn: undefined,
                couponId: undefined,
                totalPrice: undefined,
                returnPrice: undefined,
                orderStatus: undefined,
                phone: undefined,
                remark: undefined,
                recordAt: undefined,
            };
            this.resetForm("form");
        },
        orderStatusFormat(row) {
            return this.selectDictLabel(
                this.orderStatusOptions,
                row.orderStatus
            );
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageIndex = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加用户订单表";
            this.isEdit = false;
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.orderId);
            this.selection = selection;
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const orderId = row.orderId || this.ids;
            getBwOrder(orderId).then((response) => {
                this.form = response.data;
                this.open = true;
                this.title = "订单详情";
                this.isEdit = true;
                this.isVerify = false;
            });
        },
        handleVerify(row) {
            this.reset();
            const orderId = row.orderId || this.ids;
            getBwOrder(orderId).then((response) => {
                response.data.orderStatus = 3;
                this.form = response.data;
                this.open = true;
                this.title = "订单审核";
                this.isEdit = false;
                this.isVerify = true;
            });
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.orderId !== undefined) {
                        let temp = { ...this.form };
                        temp.recordAt = temp.recordAt.split(" ")[0];
                        updateBwOrder(this.form.orderId, temp).then(
                            (response) => {
                                if (response.code === 200) {
                                    this.msgSuccess(
                                        (this.isEdit ? "修改" : "审核") + "成功"
                                    );
                                    this.open = false;
                                    this.getList();
                                } else {
                                    this.msgError(response.msg);
                                }
                            }
                        );
                    } else {
                        addBwOrder(this.form).then((response) => {
                            if (response.code === 200) {
                                this.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            } else {
                                this.msgError(response.msg);
                            }
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const Ids = row.orderId || this.ids;
            this.$confirm('是否确认删除编号为"' + Ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(function () {
                    return delBwOrder(Ids);
                })
                .then(() => {
                    this.getList();
                    this.msgSuccess("删除成功");
                })
                .catch(function () {});
        },
    },
};
</script>

<style lang="scss" scoped>
.card_wrap ::v-deep {
    .el-card__header,
    .el-card__body {
        font-size: 14px;
        text-align: center;
        padding: 8px 0 !important;
        min-height: 1px;
    }

    .el-card__body {
        font-weight: bold;
        font-size: 20px;
        padding: 10px 0 !important;
    }
}
</style>
